package com.heima.datasync.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.common.constants.search.ArticleIndexConstants;
import com.heima.datasync.mapper.ApArticleMapper;
import com.heima.datasync.service.EsDataService;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.search.vo.SearchArticleVo;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @作者 itcast
 * @创建日期 2021/4/25 9:24
 **/
@Service
@Slf4j
public class EsDataServiceImpl implements EsDataService {
    @Autowired
    ApArticleMapper apArticleMapper;
    @Autowired
    RestHighLevelClient restHighLevelClient;
    @Override
    public ResponseResult dataInit() {

        // TODO  判断指定索引库是否存在

        // TODO  如果存在就删除掉

        // TODO  创建对应的索引库

        //1. 查询数据库所有文章数据
        List<ApArticle> allArticles = apArticleMapper.findAllArticles();
        //2. apArticle ==> SearchArticleVo
        if(allArticles == null || allArticles.size() == 0){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"没有查询到要导入的文章数据");
        }
        List<SearchArticleVo> articleVoList = allArticles.stream().map(SearchArticleVo::new).collect(Collectors.toList());
        //3. 将文章数据导入到es中
        //3.1  获取es客户端  创建批处理请求
        // 如: articles 5万条文档      切割成: 3000~5000条  批量导入一次
        // 思路:   采用分页的思想分批导入    page   pageSize=3000
        //        求出: 一共有多少页  pages
        //        按照 pages来进行for循环
        //        for ( int i = 1 ; i<=pages ) {
        //             for(j=(i - 1)*pageSize) ; j<3000){
        //                  articles
        //             }
        //        }
        BulkRequest bulkRequest = new BulkRequest(ArticleIndexConstants.ARTICLE_INDEX_NAME);
        articleVoList.forEach(vo -> {
            //3.2  将所有数据封装到批处理中
            IndexRequest indexRequest = new IndexRequest();
            // 文档ID 文档内容
            indexRequest.id(vo.getId() + "");
            indexRequest.source(JSON.toJSONString(vo), XContentType.JSON);
            bulkRequest.add(indexRequest);
        });
        //3.3  调用客户端执行批处理方法
        try {
            BulkResponse bulk = restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);
            return ResponseResult.okResult(bulk.status()); // OK 成功
        } catch (IOException e) {
            e.printStackTrace();
            log.error("批量导入索引库数据异常 ==> {}",e.getMessage());
            return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR,"批量导入索引库数据异常");
        }
    }
}
